package log

import (
	"errors"
)

type ConfFileWriter struct {
	On bool `toml:"On"`

	// 当前执行写入的日志文件名
	LogPath string `toml:"LogPath"`
	// 轮转日志名格式
	RotateLogPath string `toml:"RotateLogPath"`

	// WARNING、ERROR 级别的日志存到其它文件
	WfLogPath       string `toml:"WfLogPath"`
	RotateWfLogPath string `toml:"RotateWfLogPath"`
}

type ConfConsoleWriter struct {
	On    bool `toml:"On"`
	Color bool `toml:"Color"`
}

type LogConfig struct {
	// 日志开关级别
	Level string `toml:"LogLevel"`
	// 是否记录调用栈
	Tracing bool `toml:"tracing"`
	// 写到文件
	FW ConfFileWriter `toml:"FileWriter"`
	// 写到控制台
	CW ConfConsoleWriter `toml:"ConsoleWriter"`
}

// 用配置将日志初始化
func SetupLogInstanceWithConf(lc LogConfig, logger *Logger) (err error) {
	if lc.FW.On {
		// 普通日志存到文件
		if len(lc.FW.LogPath) > 0 {
			w := NewFileWriter()
			w.SetFileName(lc.FW.LogPath)
			w.SetPathPattern(lc.FW.RotateLogPath)
			w.SetLogLevelFloor(TRACE)
			if len(lc.FW.WfLogPath) > 0 {
				w.SetLogLevelCeil(INFO)
			} else {
				w.SetLogLevelCeil(ERROR)
			}
			logger.Register(w)
		}

		// WARNING、ERROR 级别的日志存到其它文件
		if len(lc.FW.WfLogPath) > 0 {
			wfw := NewFileWriter()
			wfw.SetFileName(lc.FW.WfLogPath)
			wfw.SetPathPattern(lc.FW.RotateWfLogPath)
			wfw.SetLogLevelFloor(WARNING)
			wfw.SetLogLevelCeil(ERROR)
			logger.Register(wfw)
		}
	}

	if lc.CW.On {
		w := NewConsoleWriter()
		w.SetColor(lc.CW.Color)
		logger.Register(w)
	}
	switch lc.Level {
	case "trace":
		logger.SetLevel(TRACE)
	case "debug":
		logger.SetLevel(DEBUG)
	case "info":
		logger.SetLevel(INFO)
	case "warning":
		logger.SetLevel(WARNING)
	case "error":
		logger.SetLevel(ERROR)
	case "fatal":
		logger.SetLevel(FATAL)
	default:
		err = errors.New("invalid log level")
	}

	logger.SetTracing(lc.Tracing)
	return
}

func SetupDefaultLogWithConf(lc LogConfig) (err error) {
	defaultLoggerInit()
	return SetupLogInstanceWithConf(lc, logger_default)
}
